#include "peer.h"

void PeerInfo::refresh_port(int num)
{
    uint16_t dst = 0;
    ports_.clear();
    if (!ok()) {
        if (!punch_done_) {
            for (int i = 0; i < num; ++i) {
                dst = num_range((cur_base_port_ + i), 1024,  65535);
                if (dst == init_base_port_) {
                    punch_done_ = true;
                    break;
                }
                ports_.insert(dst);
            }
            cur_base_port_ = num_range(dst + 1, 1024, 65535);
        }
    }
}

void PeerMgr::insert(const std::string& ip, const std::string& port, const std::string& nat)
{
    for (const auto& pi : peers_) {
        if (pi->ip() == ip) {
            pi->insert(std::stoi(port));
            return ;
        }
    }

    peers_.insert(std::make_shared<PeerInfo>(ip, port, nat));
}

void PeerMgr::refresh_peers()
{
    for (const auto& pi : peers_) {
        if (std::stoi(pi->nat()) == NAT_4  && local_nat_type_ == NAT_3) {
            pi->refresh_port(400);
        } else if (std::stoi(pi->nat()) == NAT_4  && local_nat_type_ == NAT_4) {
            pi->refresh_port(0);
        }
    }
}


